package com.woorigil.social.domain.subscribe;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

import org.springframework.stereotype.Component;

import com.woorigil.social.domain.ProviderUtils;

@Component
public class ReadMail {
//	String host = "pop.naver.com";
	String host = "imap.naver.com";
	String user = "moducoupon";
	String password = "jerry002";

	public List<Mail> execute() {
		List<Mail> mails = new ArrayList<Mail>();
		try {
			Properties props = new Properties();
			Session session = Session.getDefaultInstance(props, null);
			Store store = session.getStore("imaps");
			store.connect(host, user, password);

			Folder inbox = store.getFolder("INBOX");
			inbox.open(Folder.READ_WRITE);

			Message[] messages = inbox.getMessages();
			for (Message message : messages) {
				Mail mail = new Mail();//from, subject, sendDate, content);
				mail.setFrom(message.getFrom()[0].toString());
				mail.setProviderCode(ProviderUtils.getValueByEmail(mail.getFrom()));
				mail.setTitle(message.getSubject());
				mail.setContent(message.getContent().toString());
				mail.setSendDate(message.getSentDate());
				mail.setInsertDate(new Date());
				
				mails.add(mail);
				message.setFlag(Flag.DELETED, true);
			}
			inbox.close(false);
			store.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mails;
	}
}
